- Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathTwo_Sum.java
29 lines (23 loc) · 1.1 KB
/
Two_Sum.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//LeetCode 1. Two Sum
//Question Link - https://leetcode.com/problems/two-sum/
classSolution {
publicint[] twoSum(int[] nums, inttarget) {
intresult[] = newint[2];
//to store the numbers which have already been encountered
//key = number in array, value = index of the number
Map<Integer, Integer> seen = newHashMap<>();
for(inti = 0 ; i < nums.length ; i++){
//the number nums[i] is alreday in the array
//check if (target - nums[i]) is also in the array or not
intcomplement = target - nums[i];
//we check if we have already encountered complement or not.
if(seen.containsKey(complement)){
returnnewint[]{seen.get(complement), i};
}
//if complement does not exsist, we must store the current number in seen
//The current number could be the complement of some number to be visited further in the array
seen.put(nums[i], i);
}
returnresult;
}
}